package com.example.lab01.controller;

import com.example.lab01.entity.User;
import com.example.lab01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller // 1.注册一个Bean 2.控制层bean
//@Component // 1.组件  2.bean
//@RestController
// @RestController = @Controller + @ResponseBody
@RequestMapping("user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @PostMapping("create")
    private String create(@RequestBody User user , Model model) {
//        System.out.println(user);
        userService.create(user);
        model.addAttribute("users", userService.queryAll());
        return "user :: user_list";
//        数据插入进去之后 重新查询一下
    }

    @GetMapping("queryAll")
//    @ResponseBody //返回 JSON 数据 Object{} Array{}
    private String /*List<User>*/ queryAll(Model model) {
        model.addAttribute("users", userService.queryAll());
        return "/user";
//        return userService.queryAll();
    }

    @GetMapping("queryById/{id}")
    private String queryById(@PathVariable int id, Model model) {
        User user = userService.queryById(id);
        model.addAttribute("user", user);
        session.setAttribute("id", user.getId()); // request
        return "/edit";
    }

    @PostMapping("modify")
    private String modify(User user, Model model) {
        user.setId((Integer) session.getAttribute("id"));
        userService.modify(user);
        model.addAttribute("users", userService.queryAll());
        return "/user";
    }

    @GetMapping("removeById/{id}")
    private String removeById(@PathVariable int id, Model model) {
        userService.removeById(id);
        model.addAttribute("users", userService.queryAll());
        return "/user";
    }
}
